/**
* Created by li hong 2017/10/10 0025.
*/

$(function () {
    var table = new tableFactory();
    addListeners(table);
    $('#btn-export').on('click', function () {
        window.location.href="../windManage/export";
    });
    /*$('#btn-upload').on('click',function () {

    });*/
     upload();


});

function tableFactory() {
    var me = this;
    me.data = null;
    me.maxId = 0;
    var init = function () {
        $("#wind").bootstrapTable({
            method: 'get',					  //请求方式（*）
            striped: true,					  //是否显示行间隔色
            cache: false,					   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,				   //是否显示分页（*）
            sortable: true,					 //是否启用排序
            sortOrder: "asc",				   //排序方式
            sidePagination: "client",		   //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,					   //初始化加载第一页，默认第一页
            search: true,					   //是否显示表格搜索，只能进行客户端搜索
            strictSearch: false,                //true为全匹配，false为模糊查询
            showColumns: false,				  //是否显示筛选列按钮
            showRefresh: false,				  //是否显示刷新按钮
            clickToSelect: true,				//是否启用点击选中行
            showToggle: false,					//是否显示详细视图和列表视图的切换按钮
            cardView: false,					//是否显示详细视图
            detailView: false,				   //是否显示父子表
            singleSelect: true,
            height: 'auto',
            pageSize: 10,
            pageList: [5,10,20],
            columns: [{
                field: 'check', checkbox: true
               /* formatter :function stateFormatter(value, row, index) {
                                if (row.farmid == 1)
                                    return {
                                        checked : true//设置选中
                                    };
                        return value;
                    }*/
            }, {
                title: '电场主键', field: 'farmid', align: 'center', valign: 'middle', sortable: true
            }, /*{
                title: '电场编号', field: 'farmcode', align: 'center', valign: 'middle'
            },*/ {
                title: '风电场名称', field: 'farmname', align: 'center', width: '70%'
            }, {
                title: '地址', field: 'farmaddress', align: 'center'
            }, {
                title: '所属县', field: 'farmcounty', align: 'center'
            }, {
                title: '经度', field: 'lon', align: 'center'
            }, {
                title: '纬度', field: 'lat', align: 'center'
            }, {
                title: '高程(m)', field: 'alt', align: 'center'
            }, {
                title: '装机容量(m)', field: 'installedcapacity', align: 'center'
            }, {
                title: '预报算法ID', field: 'pfid', align: 'center'
            }, {
                title: '超短期预报选择', field: 'cdqforcastselect', align: 'center',
                formatter: function (value) {
                    if(value === 0){
                        return "本地算法";
                    }else if(value === 1){
                        return "逐小时算法";
                    }else if(value === 2){
                        return "云端下载";
                    }else if(value === 3){
                        return "自定义";
                    }else {
                        return "";
                    }
                }
            }, {
                title: '数值预报入库路径', field: 'nwppath', align: 'center'
            },{
                title: '实况入库路径', field: 'powerskpath', align: 'center'
            },{
                title: '测风塔入库路径', field: 'metskpath', align: 'center'
            },{
                title: '备注', field: 'remark', align: 'center'
            }
            , {
                title: '电站类型', field: 'farmtype', align: 'center',
                    formatter: function (value) {
                        return value === 1 ? '光伏' : (value === 0 ? '风电' : '');
                    }
               /* formatter: function (value, row, index) {
                    if(row.farmtype==1){
                        return "风电";
                    }else {
                        return "光伏";
                    }
                   /!* me.setMaxDepartmentId(row.departmentid);
                    return me.getParentDeptName(row.deptparentid);*!/
                }*/
            }]
        });
        me.loadData();
    }
    init();
}

tableFactory.prototype = {
    loadData: function () {
        var me = this;
        $.getJSON('../windManage/selectAll', '', function (_data) {
            me.data = _data;
            $("#wind").bootstrapTable("load", _data);
        })
    },
    setMaxUserId: function (id) {
        if (id > this.maxId) {
            this.maxId = id;
        }
    },
    getParentDeptName: function (id) {
        var name = '';
        id = parseInt(id);
        $.each(this.data, function (index, item) {
            if (item.departmentid === id) {
                name = item.deptname;
                return false;
            }
        });
        return name;
    },
    save: function () {
        var me = this;
        var html = [];
        html.push('<div style="margin: 10px;"><table class="table table-bordered table-normal">');
     /*   html.push('<tr><td>电场编号：</td><td><input type="text" class="form-control" id="new-farmcode" /></td></tr>');*/
        html.push('<tr><td>电场名称：</td><td><input type="text" class="form-control" id="new-farmname" /></td></tr>');
        html.push('<tr><td>地址：</td><td><input type="text" class="form-control" id="new-farmaddress" /></td></tr>');
        html.push('<tr><td>所属县：</td><td><input type="text" class="form-control" id="new-farmcounty" /></td></tr>');
        html.push('<tr><td>经度：</td><td><input type="text" class="form-control" id="new-lon" /></td></tr>');
        html.push('<tr><td>纬度：</td><td><input type="text" class="form-control" id="new-lat" /></td></tr>');
        html.push('<tr><td>高程(m)：</td><td><input type="text" class="form-control" id="new-alt" /></td></tr>');
        html.push('<tr><td>装机容量(mw)：</td><td><input type="text" class="form-control" id="new-installedcapacity" /></td></tr>');
        html.push('<tr><td>预报算法ID：</td><td><input type="text" class="form-control" id="new-pfid" value="1"/></td></tr>');
        html.push('<tr><td>超短期预报选择：</td><td><select type="text" class="form-control" id="new-cdqforcastselect">');
        html.push('<option value="0">本地计算</option>');
        html.push('<option value="1">逐小时计算</option>');
        html.push('<option value="2">云端下载</option>');
        html.push('<option value="3">自定义</option>');
        html.push('<tr><td>数值预报路径：</td><td><input type="text" class="form-control" id="new-nwppath" /></td></tr>');
        html.push('<tr><td>实况路径：</td><td><input type="text" class="form-control" id="new-powerskpath" /></td></tr>');
        html.push('<tr><td>测风塔路径：</td><td><input type="text" class="form-control" id="new-metskpath" /></td></tr>');

        html.push('<tr><td>备注：</td><td><input type="text" class="form-control" id="new-remark" /></td></tr>');
        html.push('<tr><td>电站类型：</td><td><select type="text" class="form-control" id="new-farmtype">');
        html.push('<option value="0">风电</option>');
        html.push('<option value="1">光伏</option>');

      /* var type;
        $.each(me.data, function (index, item) {
           if(item.farmtype==1){
               type="风电";
           }else{
               type="光伏";
           }
            html.push('<option value="">' + type + '</option>');
        });*/
        html.push('</select></td></tr>');
        html.push('</table></div>');
        html.push('<div class="pay_lose">&nbsp;&nbsp;注：添加路径后需重启采集程序</div>');

        layer.open({
            type: 1,
            area: '500px',
            title: '添加电站',
            btn: ['确定'],
            //shadeClose: true,//开启遮罩关闭
            content: html.join(''),
            yes: function (index) {
                var p = {
                    //departmentid: me.maxId + 1,
                    farmid:"",
                 /*   farmcode: $("#new-farmcode").val(),*/
                    farmname: $("#new-farmname").val(),
                    farmaddress: $("#new-farmaddress").val(),
                    farmcounty: $("#new-farmcounty").val(),
                    lon: $("#new-lon").val(),
                    lat: $("#new-lat").val(),
                    alt: $("#new-alt").val(),
                    installedcapacity: $("#new-installedcapacity").val(),
                    pfid: $("#new-pfid").val(),
                    nwppath: $("#new-nwppath").val(),
                    powerskpath: $("#new-powerskpath").val(),
                    metskpath: $("#new-metskpath").val(),
                    remark: $("#new-remark").val(),
                    farmtype:$("#new-farmtype").val(),
                    cdqforcastselect:$("#new-cdqforcastselect").val()
                };
                layer.close(index);
                $.ajax({
                    url : "../windManage/insert",
                    type : "post",
                    contentType : "application/json",
                    dataType : "json",
                    data : JSON.stringify(p),//转换成字符串。后台使用了RequestBody注解
                    success : function(data) {
                        if (data === true) {
                            me.loadData();
                            layer.msg("添加成功！", {icon: 1});
                        } else {
                            layer.msg("添加失败！", {icon: 2});
                        }
                    },
                    error :function(){
                        alert("添加失败");
                    }
                });
                /*$.post("department/insert", p, function (data) {
                    if (data === true) {
                        me.loadData();
                        layer.msg("添加成功！", {icon: 1});
                    } else {
                        layer.msg("添加失败！", {icon: 2});
                    }
                })*/

            }
        });
    },
    delete: function () {
        var me = this;
        var selects = $('#wind').bootstrapTable("getSelections");
        if (selects.length > 0) {
            layer.confirm('确定删除?', {icon: 3, title:'提示'}, function (index) {
                //do something
                var deletes = [];
                var id;
                $.each(selects, function (index, item) {
                    deletes.push({
                        farmid: item.farmid,
                        /*deptparentid: item.deptparentid,
                        deptname: item.deptname,
                        deptdesc: item.deptdesc,
                        address: item.address,
                        remarks: ""*/
                    });
                    id = item.farmid;
                    //alert(item.departmentid+""+item.deptname+item.deptdesc+item.address+item.deptparentid);
                   // alert(id);
                });
                $.ajax({
                    url: '../windManage/delete',
                    type: 'GET',
                    contentType : 'application/json;charset=utf-8', //设置请求头信息
                    dataType: 'json',
                    data: {"id":id},/*JSON.stringify(deletes)*/
                    success: function (data) {
                        if (data === true) {
                            me.loadData();
                            layer.msg("删除成功！", {icon: 1});
                        }
                    }
                });
                layer.close(index);
            });
        } else {
            layer.msg("请选择要删除的部门！", {icon: 0});
        }
    },
    edit: function () {
        var me = this;
        var selects = $('#wind').bootstrapTable("getSelections");
        var len = selects.length;
        if (len === 1) {
            var editItem = selects[0];
            console.log(editItem.farmtype);
            var html = [];
            html.push('<div style="margin: 10px;"><table class="table table-bordered table-normal">');
/*
            html.push('<tr><td>电场编号：</td><td><input type="text" class="form-control" id="edit-farmcode" /></td></tr>');
*/
            html.push('<tr><td>电场名称：</td><td><input type="text" class="form-control" id="edit-farmname" /></td></tr>');
            html.push('<tr><td>地址：</td><td><input type="text" class="form-control" id="edit-farmaddress" /></td></tr>');
            html.push('<tr><td>所属县：</td><td><input type="text" class="form-control" id="edit-farmcounty" /></td></tr>');
            html.push('<tr><td>经度：</td><td><input type="text" class="form-control" id="edit-lon" /></td></tr>');
            html.push('<tr><td>纬度：</td><td><input type="text" class="form-control" id="edit-lat" /></td></tr>');
            html.push('<tr><td>高程(m)：</td><td><input type="text" class="form-control" id="edit-alt" /></td></tr>');
            html.push('<tr><td>装机容量(mw)：</td><td><input type="text" class="form-control" id="edit-installedcapacity" /></td></tr>');
            html.push('<tr><td>预报算法ID：</td><td><input type="text" class="form-control" id="edit-pfid" /></td></tr>');
            html.push('<tr><td>超短期预报选择：</td><td><select type="text" class="form-control" id="edit-cdqforcastselect">');
            if(editItem.cdqforcastselect==0){
                html.push('<option value="0" selected>本地计算</option>');
                html.push('<option value="1">逐小时计算</option>');
                html.push('<option value="2">云端下载</option>');
                html.push('<option value="3">自定义</option>');
            }else if(editItem.cdqforcastselect==1){
                html.push('<option value="0" >本地计算</option>');
                html.push('<option value="1" selected>逐小时计算</option>');
                html.push('<option value="2">云端下载</option>');
                html.push('<option value="3">自定义</option>');
            }else if(editItem.cdqforcastselect==2){
                html.push('<option value="0">本地计算</option>');
                html.push('<option value="1">逐小时计算</option>');
                html.push('<option value="2" selected>云端下载</option>');
                html.push('<option value="3">自定义</option>');
            }else if(editItem.cdqforcastselect==3){
                html.push('<option value="0">本地计算</option>');
                html.push('<option value="1">逐小时计算</option>');
                html.push('<option value="2">云端下载</option>');
                html.push('<option value="3" selected>自定义</option>');
            }
            html.push('<tr><td>数值预报路径：</td><td><input type="text" class="form-control" id="edit-nwppath" /></td></tr>');
            html.push('<tr><td>实况路径：</td><td><input type="text" class="form-control" id="edit-powerskpath" /></td></tr>');
            html.push('<tr><td>测风塔路径：</td><td><input type="text" class="form-control" id="edit-metskpath" /></td></tr>');
            html.push('<tr><td>备注：</td><td><input type="text" class="form-control" id="edit-remark" /></td></tr>');
            html.push('<tr><td>电站类型：</td><td><select type="text" class="form-control" id="edit-farmtype">');
             if(editItem.farmtype==1){
                 html.push('<option value="0" selected>风电</option>');
                 html.push('<option value="1">光伏</option>');
             }else if(editItem.farmtype==0){
                 html.push('<option value="0">风电</option>');
                 html.push('<option value="1" selected>光伏</option>');
             }
            html.push('</select></td></tr>');
            html.push('</table></div>');
            html.push('<div class="pay_lose">&nbsp;&nbsp;注：修改路径后需重启采集程序</div>');

            layer.open({
                type: 1, area: '500px', title: '修改电站', btn: ['确定'],
                content: html.join(''),
                success: function () {

                    //$('#edit-farmcode').val(editItem.farmcode);

                    $('#edit-farmname').val(editItem.farmname);
                    $('#edit-farmaddress').val(editItem.farmaddress);
                    $('#edit-farmcounty').val(editItem.farmcounty);
                    $('#edit-lon').val(editItem.lon);
                    $('#edit-lat').val(editItem.lat);
                    $('#edit-alt').val(editItem.alt);
                    $('#edit-installedcapacity').val(editItem.installedcapacity);
                    $('#edit-pfid').val(editItem.pfid);
                    $('#edit-nwppath').val(editItem.nwppath);
                    $('#edit-powerskpath').val(editItem.powerskpath);
                    $('#edit-metskpath').val(editItem.metskpath);
                    $('#edit-remark').val(editItem.remark);
                    $('#edit-farmtype').val(editItem.farmtype);
                    $('#edit-cdqforcastselect').val(editItem.cdqforcastselect);

                },
                yes: function (index) {
                    var p = {
                        farmid: editItem.farmid,
                        //farmcode: $("#edit-farmcode").val(),
                        farmname: $("#edit-farmname").val(),
                        farmaddress: $("#edit-farmaddress").val(),
                        farmcounty: $("#edit-farmcounty").val(),
                        lon: $("#edit-lon").val(),
                        lat: $("#edit-lat").val(),
                        alt: $("#edit-alt").val(),
                        installedcapacity: $("#edit-installedcapacity").val(),
                        pfid: $("#edit-pfid").val(),
                        nwppath: $("#edit-nwppath").val(),
                        powerskpath: $("#edit-powerskpath").val(),
                        metskpath: $("#edit-metskpath").val(),
                        remark: $("#edit-remark").val(),
                        farmtype:$("#edit-farmtype").val(),
                        cdqforcastselect:$("#edit-cdqforcastselect").val()
                    };
                    layer.close(index);
                    $.ajax({
                        url : "../windManage/update",
                        type : "POST",
                        contentType : "application/json",
                        dataType : "json",
                        data : JSON.stringify(p),//转换成字符串。后台使用了RequestBody注解
                        success : function(data) {
                            if (data === true) {
                                me.loadData();
                                layer.msg("修改成功！", {icon: 1});
                            } else {
                                layer.msg("修改失败！", {icon: 2});
                            }
                        },
                        error :function(){
                            alert("添加失败");
                        }
                    });
                }
            });
        } else if (len > 1){
            layer.msg("只能选择一个部门！", {icon: 0});
        } else if (len === 0) {
            layer.msg("请选择要修改的部门！", {icon: 0});
        }
    }
};

function addListeners (tableObj) {
    $('#btn-add').off('click');
    $('#btn-delete').off('click');
    $('#btn-edit').off('click');
    $('#btn-add').on('click', function () {
        tableObj.save();
    });
    $('#btn-delete').on('click', function () {
        tableObj.delete();
    });
    $('#btn-edit').on('click', function () {
        tableObj.edit();
    });
}

function upload(){
    layui.use('upload', function(){
        var upload = layui.upload;
        //执行实例
        var uploadInst = upload.render({
            elem: '#btn-upload', //绑定元素
            url: '../windManage/CsvImport', //上传接口
            accept: 'file',//指定允许上传的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
            exts:'csv',//指定文件的后缀
            done: function(res){
                if (res === true) {
                    layer.msg("上传成功！", {icon: 1});
                } else {
                    layer.msg("上传失败！", {icon: 2});
                }
            }
            ,error: function(){
                //请求异常回调
            }
        });
    });
}


/*function changeTableSelect(staffId){
            var data = $('#wind').DataTable().rows().nodes();
            var data2 = $('#wind').DataTable().rows().data();
             $(data).each(function(index,item){
                     if(data2[index].STAFF_ID==staffId){
                             $(item).addClass('selected');
                         }else{
                             $(item).removeClass('selected');
                        }
                   });
         }*/
